﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace LinCode
{
    public class PropertiesUtils
    {

        private static Dictionary<Type, Dictionary<string, string>> cache = new Dictionary<Type, Dictionary<string, string>>();

        public static string GetDescByProperties(object p)
        {
            var type = p.GetType();
            if (!cache.ContainsKey(type))
            {
                Cache(type);
            }
            var fieldNameToDesc = cache[type];
            var fieldName = p.ToString();
            return fieldNameToDesc.ContainsKey(fieldName) ? fieldNameToDesc[fieldName] : string.Format("Can not found such desc for field `{0}` in type `{1}`", fieldName, type.Name);
        }

        private static void Cache(Type type)
        {
            var dict = new Dictionary<string, string>();
            cache.Add(type, dict);
            var fields = type.GetFields();
            foreach (var field in fields)
            {
                var objs = field.GetCustomAttributes(typeof(PropertiesDesc), true);
                if (objs.Length > 0)
                {
                    dict.Add(field.Name, ((PropertiesDesc)objs[0]).Desc);
                }
            }
        }


    }
}
